// utils/api.js - API请求工具类

const app = getApp();

/**
 * 检查网络连接状态
 */
function checkNetworkStatus() {
  return new Promise((resolve, reject) => {
    wx.getNetworkType({
      success(res) {
        console.log('网络类型:', res.networkType);
        if (res.networkType === 'none') {
          reject(new Error('网络连接不可用'));
        } else {
          resolve(res.networkType);
        }
      },
      fail(err) {
        console.error('获取网络状态失败:', err);
        reject(err);
      }
    });
  });
}

/**
 * 测试后端服务器连通性
 */
async function testServerConnection() {
  try {
    await checkNetworkStatus();
    console.log('网络连接正常，测试服务器连通性...');
    
    // 尝试一个简单的健康检查请求
    const response = await request('/health', {}, 'GET');
    console.log('服务器连通性测试成功:', response);
    return true;
  } catch (error) {
    console.error('服务器连通性测试失败:', error);
    return false;
  }
}

/**
 * 网络诊断工具
 */
async function diagnoseNetwork() {
  const diagnosis = {
    timestamp: new Date().toISOString(),
    networkType: null,
    serverReachable: false,
    issues: []
  };
  
  try {
    // 检查网络类型
    const networkType = await checkNetworkStatus();
    diagnosis.networkType = networkType;
    console.log('网络诊断 - 网络类型:', networkType);
    
    if (networkType === 'none') {
      diagnosis.issues.push('无网络连接');
      return diagnosis;
    }
    
    // 检查服务器连通性
    const serverReachable = await testServerConnection();
    diagnosis.serverReachable = serverReachable;
    
    if (!serverReachable) {
      diagnosis.issues.push('服务器不可达');
      diagnosis.issues.push('建议检查服务器地址: ' + app.globalData.baseUrl);
    }
    
    // 检查网络质量
    if (networkType === '2g') {
      diagnosis.issues.push('网络质量较差(2G)，可能导致请求超时');
    }
    
  } catch (error) {
    console.error('网络诊断失败:', error);
    diagnosis.issues.push('网络诊断失败: ' + error.message);
  }
  
  console.log('网络诊断结果:', diagnosis);
  return diagnosis;
}

/**
 * 通用请求方法（带重试机制）
 */
function request(url, data = {}, method = 'POST', retryCount = 0) {
  return new Promise((resolve, reject) => {
    const fullUrl = `${app.globalData.baseUrl}${url}`;
    const maxRetries = 2; // 最大重试次数
    
    console.log(`发起API请求: ${method} ${fullUrl} (尝试 ${retryCount + 1}/${maxRetries + 1})`, data);
    
    wx.request({
      url: fullUrl,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      timeout: 30000, // 30秒超时
      success(res) {
        console.log(`API请求成功 ${url}:`, {
          statusCode: res.statusCode,
          data: res.data,
          header: res.header
        });
        
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 404) {
          console.error(`接口不存在: ${fullUrl}`);
          reject(new Error(`接口不存在: ${url}`));
        } else if (res.statusCode === 500) {
          console.error(`服务器内部错误: ${fullUrl}`);
          reject(new Error(`服务器内部错误`));
        } else {
          console.error(`请求失败，状态码: ${res.statusCode}`, res.data);
          reject(new Error(`请求失败，状态码: ${res.statusCode}`));
        }
      },
      fail(err) {
        console.error(`API请求失败 ${url}:`, {
          errMsg: err.errMsg,
          errno: err.errno,
          url: fullUrl,
          retryCount: retryCount
        });
        
        // 如果是超时错误且还有重试次数，则重试
        if (err.errMsg.includes('timeout') && retryCount < maxRetries) {
          console.log(`请求超时，${2000 * (retryCount + 1)}ms后重试...`);
          setTimeout(() => {
            request(url, data, method, retryCount + 1)
              .then(resolve)
              .catch(reject);
          }, 2000 * (retryCount + 1)); // 递增延迟重试
          return;
        }
        
        // 根据错误类型提供更具体的提示
        let errorMessage = '网络请求失败';
        if (err.errMsg.includes('timeout')) {
          errorMessage = '请求超时，服务器响应较慢或网络不稳定';
        } else if (err.errMsg.includes('fail')) {
          errorMessage = '网络连接失败，请检查网络设置';
        } else if (err.errMsg.includes('abort')) {
          errorMessage = '请求被中断';
        }
        
        // 只在最后一次尝试失败时显示错误提示
        if (retryCount >= maxRetries) {
          wx.showToast({
            title: errorMessage,
            icon: 'error',
            duration: 3000
          });
        }
        
        reject(err);
      }
    });
  });
}

/**
 * 用户资料列表查询
 * POST: /matchmaking/userprofile/query
 * 入参：QueryUserprofileRequest {}
 * 返回：QueryUserprofileResponse { code, msg, data: { userprofileList: UserProfile[], totalNum: int } }
 * UserProfile新增字段：verified (int) - 1:验证过的会员；2:未验证的非会员
 */
function queryUserprofile(params = {}) {
  const defaultParams = {
    pageNum: 1,
    pageSize: 20
  };
  return request('/matchmaking/userprofile/query', { ...defaultParams, ...params });
}

/**
 * 用户资料详情查询
 * POST: /matchmaking/userprofile/query
 * 入参：{ userNumList: int[] }
 * 返回：QueryUserprofileResponse { code, msg, data: { userprofileList: UserProfile[], totalNum: int } }
 * UserProfile新增字段：verified (int) - 1:验证过的会员；2:未验证的非会员
 */
function getUserProfile(userNum) {
  return request('/matchmaking/userprofile/query', {
    userNumList: [userNum]
  });
}

/**
 * 保存/更新用户资料
 */
function syncUserProfile(userProfile) {
  return request('/matchmaking/userprofile/sync', userProfile);
}

/**
 * 查询择偶标准
 */
function queryMatePreference(userNum) {
  return request('/matchmaking/matepreference/query', {
    userNumList: [userNum]
  });
}

/**
 * 保存择偶标准
 */
function syncMatePreference(matePreference) {
  return request('/matchmaking/matepreference/sync', {
    matePreference: matePreference
  });
}

/**
 * 送花接口
 */
function sendFlower(currentUserId, targetUserId) {
  return request('/matchmaking/flower/send', {
    currentUserId: currentUserId,
    targetUserId: targetUserId
  });
}

/**
 * 获取送花统计
 */
function getFlowerStats(userNum) {
  return request('/matchmaking/flower/stats', {
    userNum: userNum
  });
}

/**
 * 获取收花统计
 */
function getReceivedFlowerStats() {
  return request('/matchmaking/flower/received/stats', {});
}

/**
 * 获取收花记录
 */
function getReceivedFlowerRecords(params = {}) {
  const defaultParams = {
    pageNum: 1,
    pageSize: 20
  };
  return request('/matchmaking/flower/received/records', { ...defaultParams, ...params });
}

/**
 * 获取送花统计
 */
function getSentFlowerStats() {
  return request('/matchmaking/flower/sent/stats', {});
}

/**
 * 获取送花记录
 */
function getSentFlowerRecords(params = {}) {
  const defaultParams = {
    pageNum: 1,
    pageSize: 20
  };
  return request('/matchmaking/flower/sent/records', { ...defaultParams, ...params });
}

/**
 * 获取最后一次送花时间
 */
function getLastFlowerTime() {
  return request('/matchmaking/flower/last-time', {});
}

/**
 * 获取今日推荐用户
 */
function getTodayRecommendations() {
  return queryUserprofile({
    pageNum: 1,
    pageSize: 6
  });
}

/**
 * 获取验证用户列表
 */
function getVerifiedUsers(params = {}) {
  return queryUserprofile({
    ...params,
    // 可以添加验证用户的特定筛选条件
  });
}

/**
 * 获取未验证用户列表
 * POST: /matchmaking/unverified/userprofile/query
 * 入参：QueryUserprofileRequest {}
 * 返回：QueryUserprofileResponse { code, msg, data: { userprofileList: UserProfile[], totalNum: int } }
 * UserProfile新增字段：verified (int) - 1:验证过的会员；2:未验证的非会员
 */
function getUnverifiedUsers(params = {}) {
  const defaultParams = {
    pageNum: 1,
    pageSize: 20
  };
  return request('/matchmaking/unverified/userprofile/query', { ...defaultParams, ...params });
}

/**
 * 今日特别推荐接口
 * GET: /matchmaking/match/recommend
 * 入参：RecommendUserprofileRequest {}
 * 返回：RecommendUserprofileResponse { code, msg, data: { recommendList: UserProfile[] } }
 */
function getRecommendUserprofile() {
  return request('/matchmaking/match/recommend', {}, 'GET');
}

module.exports = {
  request,
  checkNetworkStatus,
  testServerConnection,
  diagnoseNetwork,
  queryUserprofile,
  getUserProfile,
  syncUserProfile,
  queryMatePreference,
  syncMatePreference,
  sendFlower,
  getFlowerStats,
  getReceivedFlowerStats,
  getReceivedFlowerRecords,
  getSentFlowerStats,
  getSentFlowerRecords,
  getLastFlowerTime,
  getTodayRecommendations,
  getRecommendUserprofile,
  getVerifiedUsers,
  getUnverifiedUsers
};